package rabbitmq.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerDemo {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.创建连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("8.130.35.237");
        connectionFactory.setPort(5672); //需要提前开放端口号
        connectionFactory.setUsername("study"); //账号
        connectionFactory.setPassword("study"); //密码
        connectionFactory.setVirtualHost("test"); //虚拟主机
        Connection connection = connectionFactory.newConnection();
        //2.创建Channel
        Channel channel = connection.createChannel();
        //3.申明队列(可以省略)
//        channel.queueDeclare("hello", true, false, false, null);

        //4.消费消息
        /**
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         * 参数说明
         * queue:要消费的队列名称
         * autoAck:是否自动确认, 消费者收到信息后, 自动和MQ确认
         * callback:接收到消息后执行的逻辑
         */
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            //从队列中收到消息, 就会执行方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息: " + new String(body));
            }
        };
        String s = channel.basicConsume("hello", true, consumer);

        //等待程序执行完成
        Thread.sleep(20000);

        //5.释放资源
        channel.close();
        connection.close();
    }
}
